package per.lee.spingboothelper.common.export;


import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportExcelUtils {

    public static void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName, ExcelData data) throws Exception {
        ExportBaseUtils.exportInit(request,response,fileName);
        exportExcel(data, response.getOutputStream());
    }

    public static void exportExcel(ExcelData data, OutputStream out) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);
            wb.write(out);
        } finally {

            out.close();
            wb.close();

        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
        int rowIndex = ExportBaseUtils.writeTitlesToExcel(wb, sheet, data.getTitles());
        ExportBaseUtils.writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
//        ExportBaseUtils.autoSizeColumns(sheet, data.getTitles().size() + 1);

    }



}

